package com.example.contactcloud;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.contactcloud.R;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;


public class EditGroups extends Activity {
	
	static final String EXTRA_MESSAGE="";
	private static final String PHP_UPDATEGROUP = "http://softeng.cs.uwosh.edu/students/baurj00/PHPUpdateGroup.php";
	String loginStatus = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(LoginActivity.globalTheme);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_groups);
		
		Intent i = getIntent();
		loginStatus = i.getStringExtra(EXTRA_MESSAGE);
		
		//Get all groups
		new GetAllGroupsTask().execute();
		
		//Navigates back to AllContacts
		Button cancelButton = (Button) findViewById(R.id.cancelButton);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				close();
			}
		});
		
		Button saveButton = (Button) findViewById(R.id.saveButton);
		saveButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				String whatever = "";
				new PutAllGroupsTask().execute();
				new UpdateTime().execute();
				close();
			}
		});
		
	}

	private void close(String status)
	{
		if (status.equals("true")){
			new UpdateGroups().execute();
		}
		this.finish();
	}
	
	private void close()
	{
		this.finish();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_edit_groups, menu);
		return true;
	}
	
	private class GetAllGroupsTask extends AsyncTask<Void, Integer, ArrayList<Group>>{

		@Override
		protected ArrayList<Group> doInBackground(Void... nothing) {
			
			ContactsDataSource cds2 = new ContactsDataSource(EditGroups.this);
			
			cds2.open();
			
			ArrayList<Group> groups = cds2.getAllGroups();
			
			cds2.close();
			
			return groups;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Group> groupList) {
        	EditText editGroup1 = (EditText) findViewById(R.id.editGroup1);
        	EditText editGroup2 = (EditText) findViewById(R.id.editGroup2);
        	EditText editGroup3 = (EditText) findViewById(R.id.editGroup3);
        	EditText editGroup4 = (EditText) findViewById(R.id.editGroup4);
        	EditText editGroup5 = (EditText) findViewById(R.id.editGroup5);
        	editGroup1.setText(groupList.get(1).getGroupName());
    		editGroup2.setText(groupList.get(2).getGroupName());
    		editGroup3.setText(groupList.get(3).getGroupName());
    		editGroup4.setText(groupList.get(4).getGroupName());
    		editGroup5.setText(groupList.get(5).getGroupName());
        }
        
	}
	
	private class UpdateTime extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			
			ContactsDataSource cds = new ContactsDataSource(EditGroups.this);
			
			cds.open();
			
			cds.updateTime();
			
			cds.close();
			return null;
		}

		
	}
        
    	private class PutAllGroupsTask extends AsyncTask<Void, Integer, String>{

    		@Override
    		protected String doInBackground(Void... nothing) {
    			
    			ContactsDataSource cds2 = new ContactsDataSource(EditGroups.this);
    			
    			cds2.open();
    			
            	EditText editGroup1 = (EditText) findViewById(R.id.editGroup1);
            	EditText editGroup2 = (EditText) findViewById(R.id.editGroup2);
            	EditText editGroup3 = (EditText) findViewById(R.id.editGroup3);
            	EditText editGroup4 = (EditText) findViewById(R.id.editGroup4);
            	EditText editGroup5 = (EditText) findViewById(R.id.editGroup5);
            	Group g1 = new Group(2,editGroup1.getText().toString());
            	Group g2 = new Group(3,editGroup2.getText().toString());
            	Group g3 = new Group(4,editGroup3.getText().toString());
            	Group g4 = new Group(5,editGroup4.getText().toString());
            	Group g5 = new Group(6,editGroup5.getText().toString());
            	
            	try {
					cds2.updateGroups(g1);
	            	cds2.updateGroups(g2);
	            	cds2.updateGroups(g3);
	            	cds2.updateGroups(g4);
	            	cds2.updateGroups(g5);
				} catch (Exception e) {
					e.printStackTrace();
				}
    			
    			cds2.close();
				return "";
    		}
    		
    		protected void onPostExecute(String whatever)
    		{
    			if (!loginStatus.equals("false")){
    				new UpdateGroups().execute();
    			}
    		}
    	}
    	
    	private class UpdateGroups extends AsyncTask<Void, Void, Boolean> 
    	{
    		@Override
    		protected Boolean doInBackground(Void... arg0) 
    		{
    			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    			
    			if(networkInfo != null && networkInfo.isConnected())
    			{
    				ContactsDataSource cds = new ContactsDataSource(EditGroups.this);
    				cds.open();
    				ArrayList<Group> allGroups = cds.getAllGroups();
    				cds.close();
    			
    				
    				JSONArray allJSONGroups = new JSONArray();
    				
    				String all = null;
    				
    				for(int i = 0; i < allGroups.size(); i++)
    				{
    					JSONObject jGroup = new JSONObject();
    					Group temp = allGroups.get(i);
    					try
    					{
    						jGroup.put("groupid", temp.getGroupId());
    						jGroup.put("groupname", temp.getGroupName());		
    						allJSONGroups.put(i, jGroup);	
    					}catch(Exception ex)
    					{
    						System.err.println("Cannot update #" + i + " JSON Group");
    					}
    				}
    				
    				all = allJSONGroups.toString();
    				
    				HttpClient httpClient = new DefaultHttpClient();
    				HttpPost httppost = new HttpPost(PHP_UPDATEGROUP);
     				
    				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
    				c.add(new BasicNameValuePair("json", all));
    				
    				try
    				{				
    					httppost.setEntity(new UrlEncodedFormEntity(c));
    					ResponseHandler<String> respondHandler = new BasicResponseHandler();
    					String rep = httpClient.execute(httppost, respondHandler);
    				}
    				catch(Exception e){
    					System.out.println(e.getMessage() + "FAIL");
    				}
    			}
    		
    			return null;
    		}

    	}

}
	
